import {
  deleteAccount,
  getAccountPage,
  hideAccount,
  resetAccountBindWeChat,
} from '@/services/api/api-admin-account';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Space, Switch, Tag, message } from 'antd';
import 'dayjs/locale/zh-cn';
import React, { Key, useRef, useState } from 'react';
import AddAccount from './components/AddAccount';
import EditAccount from './components/EditAccount';

export default (): React.ReactNode => {
  const [selectedAccountRowKeys, setSelectedAccountRowKeysState] = useState<React.Key[]>([]);

  const [accountIsHide, setAccountIsHideState] = useState<boolean>(false);

  const userRef = useRef<ActionType>();

  const columns: ProColumns<AdminAccountData.Account>[] = [
    {
      title: '账号',
      key: 'name',
      dataIndex: 'name',
      width: '80px',
      fixed: 'left',
    },
    {
      title: '激活',
      key: 'isActivation',
      dataIndex: 'isActivation',
      valueType: 'select',
      valueEnum: {
        0: { text: '禁用', status: 'Error' },
        1: { text: '启用', status: 'Success' },
      },
      width: '80px',
    },
    {
      title: '状态',
      key: 'state',
      dataIndex: 'state',
      valueType: 'select',
      valueEnum: {
        0: { text: '禁用', status: 'Error' },
        1: { text: '启用', status: 'Success' },
      },
      width: '80px',
    },
    {
      title: '绑定微信',
      key: 'isBindWeChat',
      dataIndex: 'isBindWeChat',
      valueType: 'select',
      valueEnum: {
        0: { text: '否', status: 'Error' },
        1: { text: '是', status: 'Success' },
      },
      width: '80px',
    },
    {
      title: '绑定公众号',
      key: 'isBindWeChatWxmp',
      dataIndex: 'isBindWeChatWxmp',
      valueType: 'select',
      valueEnum: {
        0: { text: '否', status: 'Error' },
        1: { text: '是', status: 'Success' },
      },
      width: '100px',
    },
    {
      title: '电话',
      key: 'phone',
      dataIndex: 'phone',
      width: '120px',
    },
    {
      title: '组织',
      key: 'organizationName',
      dataIndex: 'organizationName',
      width: '180px',
      render: (_, row) => (
        <Space>
          {row.organizationName && <Tag key={row.organizationId}>{row.organizationName}</Tag>}
        </Space>
      ),
    },
    {
      title: '角色',
      key: 'role',
      dataIndex: 'role',
      hideInSearch: true,
      ellipsis: true,
      render: (_, row) => (
        <Space size={[0, 'small']} wrap>
          {row.roleNames.map((item) => (
            <Tag key={item}>{item}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '最后登录时间',
      key: 'loginTime',
      dataIndex: 'loginTime',
      hideInSearch: true,
      width: 150,
    },
    {
      title: '操作',
      valueType: 'option',
      width: '120px',
      fixed: 'right',
      render: (_, row, index, action) => [
        <EditAccount
          key="edit_role"
          account={row}
          onRefurbish={() => {
            userRef.current?.reload();
          }}
        />,
        <a
          key="a_reset_bind_wechat"
          onClick={async () => {
            const response = await resetAccountBindWeChat({ id: row.id });
            if (response.code === 0) {
              message.success('重置成功');
              userRef.current?.reload();
            }
          }}
        >
          重置微信
        </a>,
      ],
    },
  ];
  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await getAccountPage(
      accountIsHide
        ? { ...params }
        : {
            ...params,
            isHide: 0,
          },
    );
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  return (
    <PageContainer
      extra={[
        <>
          隐身：
          <Switch
            key="isHide"
            checkedChildren="开启"
            unCheckedChildren="关闭"
            onChange={(value) => {
              setAccountIsHideState(value);
              userRef.current?.reset();
            }}
          />
        </>,
      ]}
    >
      <ProTable<AdminAccountData.Account>
        // ghost
        // search={false}
        columns={columns}
        actionRef={userRef}
        request={request}
        rowSelection={{
          type: 'checkbox',
          onChange: (selectedRowKeys: Key[], selectedRows: any) => {
            setSelectedAccountRowKeysState(selectedRowKeys);
          },
        }}
        sticky
        rowKey="id"
        tableLayout="fixed"
        dateFormatter="string"
        bordered
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        scroll={{
          x: '1300px',
        }}
        toolBarRender={() => [
          <AddAccount
            key="add_account"
            onRefurbish={() => {
              userRef.current?.reload();
            }}
          />,
        ]}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) =>
          selectedAccountRowKeys.length > 0 && (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                  取消
                </a>
              </span>
            </Space>
          )
        }
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a
                onClick={async () => {
                  try {
                    const response = await deleteAccount({ ids: selectedAccountRowKeys });
                    if (response.code === 0) {
                      message.success('批量删除成功');
                      setSelectedAccountRowKeysState([]);
                      userRef.current?.reload();
                      userRef?.current?.clearSelected();
                    }
                  } catch (error) {
                    message.error('批量删除失败');
                  }
                  userRef.current?.reload();
                }}
              >
                删除
              </a>

              <a
                onClick={async () => {
                  try {
                    const response = await hideAccount({ ids: selectedAccountRowKeys });
                    if (response.code === 0) {
                      message.success('批量隐藏成功');
                      setSelectedAccountRowKeysState([]);
                      userRef.current?.reload();
                      userRef?.current?.clearSelected();
                    }
                  } catch (error) {
                    message.error('批量隐藏失败');
                  }
                  userRef.current?.reload();
                }}
              >
                隐身
              </a>
            </Space>
          );
        }}
      />
    </PageContainer>
  );
};
